import React, { useState, useEffect, useContext, useCallback } from 'react';
import { Modal, Tree, message } from 'antd';
import FetchHelper from '../../../../../../utils/helper/fetch-helper';
import GlobalContext from '../../../../../../utils/GlobalContext';
import WsPlayer from '../../../../../../WsPlayer';
import './videoMonitor.less';

const VideoMonitorModal = ({ visible, onCancel, autoExpandIds = null }) => {
    const [treeData, setTreeData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [selectedNode, setSelectedNode] = useState(null);
    const [channelId, setChannelId] = useState(null);
    const [autoExpandComplete, setAutoExpandComplete] = useState(true); // 默认为true，避免无限循环

    const [currentItem, setCurrentItem] = useState(null);

    // 获取树节点数据
    const fetchTreeData = useCallback(async (parentId = '001', checkStat = 0) => {
        try {
            setLoading(true);
            const response = await FetchHelper.postJson('/admin-api/ybyj/sp/device/Tree', {
                id: parentId,
                type: "001;;1",
                checkStat: checkStat
            });
            if (response.code === 200 && response.data.success) {
                const nodes = response.data.data.value.map(node => ({
                    key: node.id,
                    title: node.name,
                    isLeaf: node.id.includes('$'),
                    icon: <img src={node.iconType} alt="" style={{ width: 16, height: 16 }} />,
                    ...node
                })).filter((node, i) => {
                    if (!parentId) {
                        return i === 0;
                    }
                    return true;
                });
                return nodes;
            }
            return [];
        } catch (error) {
            message.error('获取监控树数据失败');
            return [];
        } finally {
            setLoading(false);
        }
    }, []);

    // 加载树数据
    useEffect(() => {
        if (visible) {
            fetchTreeData().then(data => {
                setTreeData(data);
                setExpandedKeys([]);
                
                // 只有当autoExpandIds明确传入且不为null时，才标记为未完成
                if (autoExpandIds !== null && autoExpandIds.length > 0) {
                    setAutoExpandComplete(false);
                } else {
                    setAutoExpandComplete(true);
                }
            });
        }
    }, [visible, autoExpandIds, fetchTreeData]);

    // 处理自动展开
    useEffect(() => {
        const autoExpandTree = async () => {
            // 关键修复：autoExpandIds必须存在且长度>0才执行，并且要确保不是默认的空数组
            if (!autoExpandIds || autoExpandIds.length === 0 || autoExpandComplete || !visible || treeData.length === 0) {
                // 如果是空数组，直接标记为完成
                if (autoExpandIds && autoExpandIds.length === 0 && !autoExpandComplete) {
                    setAutoExpandComplete(true);
                }
                return;
            }

            try {
                // 依次展开每个层级
                let currentKeys = [...expandedKeys];
                
                for (let i = 0; i < autoExpandIds.length - 1; i++) {
                    const currentId = autoExpandIds[i];
                    
                    // 将当前ID添加到展开键中
                    if (!currentKeys.includes(currentId)) {
                        currentKeys.push(currentId);
                    }
                    
                    // 递归查找节点
                    const findNode = (nodes, id) => {
                        for (const node of nodes) {
                            if (node.key === id) {
                                return node;
                            }
                            if (node.children) {
                                const found = findNode(node.children, id);
                                if (found) return found;
                            }
                        }
                        return null;
                    };
                    
                    const currentNode = findNode(treeData, currentId);
                    
                    // 如果找不到节点或者已经是叶子节点，则中断
                    if (!currentNode || currentNode.isLeaf) {
                        break;
                    }
                    
                    // 如果节点没有子节点或子节点为空，则加载子节点
                    if (!currentNode.children || currentNode.children.length === 0) {
                        const childNodes = await fetchTreeData(currentId, currentNode.checkStat);
                        
                        // 更新树数据
                        setTreeData(prevTreeData => {
                            const updateTreeData = (list) => {
                                return list.map(node => {
                                    if (node.key === currentId) {
                                        return { ...node, children: childNodes };
                                    }
                                    if (node.children) {
                                        return { ...node, children: updateTreeData(node.children) };
                                    }
                                    return node;
                                });
                            };
                            return updateTreeData(prevTreeData);
                        });
                    }
                }
                
                // 设置展开的键
                setExpandedKeys(currentKeys);
                
                // 选中最后一个叶子节点（如果是叶子节点）
                const lastId = autoExpandIds[autoExpandIds.length - 1];
                if (lastId && lastId.includes('$')) {
                    // 递归查找节点
                    const findNode = (nodes, id) => {
                        for (const node of nodes) {
                            if (node.key === id) {
                                return node;
                            }
                            if (node.children) {
                                const found = findNode(node.children, id);
                                if (found) return found;
                            }
                        }
                        return null;
                    };
                    
                    // 等待树更新完成
                    setTimeout(() => {
                        const leafNode = findNode(treeData, lastId);
                        if (leafNode) {
                            setSelectedNode(leafNode);
                            setChannelId(leafNode.id);
                        }
                        setAutoExpandComplete(true);
                    }, 300);
                } else {
                    setAutoExpandComplete(true);
                }
            } catch (error) {
                console.error('自动展开节点失败:', error);
                setAutoExpandComplete(true);
            }
        };
        
        autoExpandTree();
    }, [treeData, autoExpandIds, autoExpandComplete, visible, expandedKeys, fetchTreeData]);

    // 实时预览
    useEffect(() => {
        const real_timePreview = async (channelId = null) => {
            try {
                const resp = await FetchHelper.postJson(`/admin-api/evo-apigw/admin/API/MTS/Video/StartVideo`, {
                    channelId: `${channelId}`
                });
                return resp;
            } catch (error) {
                console.error('获取设备数据失败:', error);
            }
            return null; // 如果出错，返回 null
        }
        if (channelId) {
            real_timePreview(channelId).then(resp => {
                setCurrentItem({
                    rtspURL: resp?.data?.outer_url,
                    wsURL: resp?.data?.wsUrL,
                    channelId: channelId    
                });
            });
        }
    }, [channelId]);

    // 处理树节点展开
    const onLoadData = (treeNode) => {
        const { key, children, checkStat } = treeNode;
        if (children) {
            return Promise.resolve();
        }

        return new Promise(resolve => {
            fetchTreeData(key, checkStat).then(childNodes => {
                setTreeData(prevTreeData => {
                    const updateTreeData = (list) => {
                        return list.map(node => {
                            if (node.key === key) {
                                return { ...node, children: childNodes };
                            }
                            if (node.children) {
                                return { ...node, children: updateTreeData(node.children) };
                            }
                            return node;
                        });
                    };
                    return updateTreeData(prevTreeData);
                });

                // 确保展开当前节点
                setExpandedKeys(prevKeys => {
                    if (!prevKeys.includes(key)) {
                        return [...prevKeys, key];
                    }
                    return prevKeys;
                });

                resolve();
            });
        });
    };

    // 处理节点选择
    const onSelect = (selectedKeys, info) => {
        const node = info.node;
        if (node.isLeaf) {
            setSelectedNode(node);
            setChannelId(node.id);
        }
    };

    // 处理展开/收起节点
    const onExpand = (expandedKeys) => {
        setExpandedKeys(expandedKeys);
    };

    // 处理关闭模态框
    const handleCancel = () => {
        // 重置状态
        setSelectedNode(null);
        setChannelId(null);
        setAutoExpandComplete(true);
        setCurrentItem(null);
        // 调用父组件的取消函数
        onCancel();
    };

    return (
        <Modal
            title="视频监控"
            open={visible}
            onCancel={handleCancel}
            width={1200}
            footer={null}
            bodyStyle={{ padding: '16px 0' }}
            className='video-monitor-modal'
        >
            <div style={{ display: 'flex', height: '600px' }}>
                <div style={{ width: '300px', borderRight: '1px solid #f0f0f0', overflow: 'auto' }}>
                    <Tree
                        loadData={onLoadData}
                        treeData={treeData}
                        onSelect={onSelect}
                        expandedKeys={expandedKeys}
                        onExpand={onExpand}
                    />
                </div>
                <div style={{ flex: 1, padding: '4px',overflow:'hidden' }}>
                    {selectedNode && currentItem ? (
                        <WsPlayer
                            playParams={currentItem}
                            width={'100%'}
                            height={'100%'} 
                        />
                    ) : (
                        <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
                            请选择监控点
                        </div>
                    )}
                </div>
            </div>
        </Modal>
    );
};

export default VideoMonitorModal; 